package com.lxk.wx.robot.task;

import cn.hutool.core.collection.ListUtil;
import com.lxk.wx.robot.Bot;
import com.lxk.wx.robot.config.WechatBotConfig;
import com.lxk.wx.robot.service.BotTaskService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author heyi
 * 2024/6/4
 */
@Component
@AllArgsConstructor
@Slf4j
public class MessageSendTask implements CommandLineRunner {

    private final BotTaskService botTaskService;
    private final WechatBotConfig wechatBotConfig;

    /**
     * 一分钟执行发送消息
     */
    @Scheduled(fixedDelay = 60000)
//    @Scheduled(cron = "0 0/1 * * * ?")
    public void sendContent() {
        List<String> msgList = botTaskService.pollWaifSendMessage();
        List<List<String>> partitionMsg = ListUtil.partition(msgList, wechatBotConfig.getMaxMsgCount());
        List<Bot> botList = botTaskService.getAll();
        for (int i = 0; i < partitionMsg.size(); i++) {
            List<String> msgs = partitionMsg.get(i);
            Bot bot = botList.get(i);
            msgs.forEach(bot::send);
        }
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("定时发送任务启动成功");
    }
}
